package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.OrdersDao;
import com.foreknow.elm.po.Business;
import com.foreknow.elm.po.Orderdetailet;
import com.foreknow.elm.po.Orders;
import com.foreknow.elm.util.CommonUtil;
import com.foreknow.elm.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 *  1. OrdersController/createOrders
 *    参数：userId、businessId、daId、orderTotal
 *    返回值：int（订单编号）
 *    功能：根据用户编号、商家编号、订单总金额、送货地址编号向订单表中添加一条记录,并获取自动生成的订单编号，
 *    ​
 *    ​           然后根据用户编号、商家编号从购物车表中查询所有数据，批量添加到订单明细表中，
 *
 *    ​           然后根据用户编号、商家编号删除购物车表中的数据。
 *      业务流程
 *    开始事务
 *      1.1 查询当前用户购物车中当前商家的所有食品信息(目的要将查询到的结果放到明细中)
 *        CartDao  listCartf(Cart cart)-----------------List<Cart>
 *     1.2 创建订单并返回订单的编号
 *        OrdersDao-----saveOrder()方法------------返回OrderId
 *     1.3 向订单明细表中批量添加数据
 *
 *       创建一个List<Orderdetail>集合
 *       遍历List<Cart>
 *       for(Cart cart:list){
 *         orderId
 *         获取到cart对象中的 foodId和数量
 *         创建Orderdetail对象，保存orderId  foodId  数量
 *         将对象添加到List<Orderdetail>集合中
 *       }
 *
 *        需要创建 OrderDetailDao和实现类
 *       public int save(List<Orderdetail> list){
 *         sql = insert into orderdetail(orderId,foodId,quantity) values (xxx,xxx,xxx),(s (xxx,xxx,xxx)xxx,xxx,xxx)
 *         StringBuffer s = new StringBuffer(sql);
 *         //遍历list集合
 *         for(){
 *           s.append("("+orderId+","+foodId+","+quantity")"+",");
 *         }
 *       }
 *    1.4 清空购物车
 *        调用cartDao中的方法:removeCart()
 *    提交事务
 */
public class OrdersDaoImpl implements OrdersDao {
    private Connection con;
    private PreparedStatement pst;
    private ResultSet rs;
    @Override
    public int createOrders(String userId, Integer businessId, Integer daId, Double orderTotal) throws SQLException {
        int orderId = 0;

        String sql = "INSERT INTO orders(userId,businessId,orderDate,daId,orderTotal) VALUES(?,?,?,?,?)";
        try {
            String date = CommonUtil.getCurrentDate();
            con = DBUtil.getConnection();
            //获取预处理对象 指定返回的主键
            pst = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pst.setString(1,userId);
            pst.setInt(2,businessId);
            pst.setString(3,date);
            pst.setInt(4,daId);
            pst.setDouble(5,orderTotal);
            pst.executeUpdate();

             rs = pst.getGeneratedKeys();
             if (rs.next()){
                 orderId = rs.getInt(1);
             }
        }finally {
            DBUtil.close(pst);
        }
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) throws SQLException {
        Orders orders = null;
        String sql = "SELECT * FROM orders,business WHERE orders.businessId = business.businessId AND orders.orderId = ?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);

            pst.setInt(1,orderId);

            rs = pst.executeQuery();

            while (rs.next()){

                Business business = new Business();
                business.setBusinessId(rs.getInt("businessId"));
                business.setBusinessName(rs.getString("businessName"));
                business.setBusinessAddress(rs.getString("businessAddress"));
                business.setBusinessExplain(rs.getString("businessExplain"));
                business.setBusinessImg(rs.getString("businessImg"));
                business.setOrderTypeId(rs.getInt("orderTypeId"));
                business.setStarPrice(rs.getDouble("starPrice"));
                business.setDeliveryPrice(rs.getDouble("deliveryPrice"));
                business.setRemarks(rs.getString("remarks"));

                orders = new Orders();
                orders.setOrderId(rs.getInt("orderId"));
                orders.setUserId(rs.getString("userId"));
                orders.setBusinessId(rs.getInt("businessId"));
                orders.setOrderDate(rs.getString("orderDate"));
                orders.setOrderTotal(rs.getDouble("orderTotal"));
                orders.setDaId(rs.getInt("daId"));
                orders.setOrderState(rs.getInt("orderState"));

                orders.setBusiness(business);
            }

        }finally {                          //这里不能处理异常，也就是没有catch，只有finally
            DBUtil.close(pst);              //这里负责关闭PreparedStatement和ResultSet
        }
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) throws SQLException {
        List<Orders> ordersList = new ArrayList<>();

        String sql = "SELECT * FROM orders,business WHERE orders.businessId = business.businessId AND orders.userId = ?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1,userId);
            rs = pst.executeQuery();
            while (rs.next()){

                Business business = new Business();
                business.setBusinessId(rs.getInt("businessId"));
                business.setBusinessName(rs.getString("businessName"));
                business.setBusinessAddress(rs.getString("businessAddress"));
                business.setBusinessExplain(rs.getString("businessExplain"));
                business.setBusinessImg(rs.getString("businessImg"));
                business.setOrderTypeId(rs.getInt("orderTypeId"));
                business.setStarPrice(rs.getDouble("starPrice"));
                business.setDeliveryPrice(rs.getDouble("deliveryPrice"));
                business.setRemarks(rs.getString("remarks"));

                Orders orders = new Orders();
                orders.setOrderId(rs.getInt("orderId"));
                orders.setUserId(rs.getString("userId"));
                orders.setBusinessId(rs.getInt("businessId"));
                orders.setOrderDate(rs.getString("orderDate"));
                orders.setOrderTotal(rs.getDouble("orderTotal"));
                orders.setDaId(rs.getInt("daId"));
                orders.setOrderState(rs.getInt("orderState"));


                orders.setBusiness(business);


                ordersList.add(orders);
            }

        }finally {                          //这里不能处理异常，也就是没有catch，只有finally
            DBUtil.close(pst);              //这里负责关闭PreparedStatement和ResultSet
        }
        return ordersList;
    }
}
